<?php

/**
  * wechat php test
  */
//define your token

require("util.php");
require("config.php");
connect_db();

define("TOKEN", "lankastories");
$wechat_obj = new wechat_callbackapi();
if (array_key_exists("echostr", $_GET))
    $wechat_obj->valid();
else
    $wechat_obj->response_msg(); 

class wechat_callbackapi{
    public function valid(){
        $echo_str = $_GET["echostr"];

        //valid signature , option
        if($this->check_signature()){
        	echo $echo_str;
        	exit;
        }
    }

    public function log_file($filename,$msg){
        //打开文件
        $fd = fopen($filename,"a");
        //增加文件
        $str = "[".date("Y/m/d h:i:s",time())."]".$msg;
        //写入字符串
        fwrite($fd, $str."\n\n");
        //关闭文件
        fclose($fd);
    }
     
    public function response_msg(){
    //get post data, May be due to the different environments
        $post_str = $GLOBALS["HTTP_RAW_POST_DATA"];
        $this->log_file("../logs/debug.log", $post_str);

        $text_tpl = "<xml>
                         <ToUserName><![CDATA[%s]]></ToUserName>
                         <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
                         <FuncFlag>0</FuncFlag>
                     </xml>";

        $news_tpl = "<xml>
                         <ToUserName><![CDATA[%s]]></ToUserName>
                         <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[news]]></MsgType>
                         <ArticleCount>%s</ArticleCount>
                         <Articles>
                         %s
                         </Articles>
                     </xml>"; 

        $music_tpl = " <xml>
                           <ToUserName><![CDATA[%s]]></ToUserName>
                           <FromUserName><![CDATA[%s]]></FromUserName>
                           <CreateTime>%s</CreateTime>
                           <MsgType><![CDATA[music]]></MsgType>
                           <Music>
                           <Title><![CDATA[%s]]></Title>
                           <Description><![CDATA[%s]]></Description>
                           <MusicUrl><![CDATA[%s]]></MusicUrl>
                           <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                           </Music>
                       </xml>";

        $each_item = "<item>
                          <Title><![CDATA[%s]]></Title> 
                          <Description><![CDATA[%s]]></Description>
                          <PicUrl><![CDATA[%s]]></PicUrl>
                          <Url><![CDATA[%s]]></Url>
                      </item>";

      	//extract post data
        if (!empty($post_str)){
            $post_obj = simplexml_load_string($post_str, "SimpleXMLElement", LIBXML_NOCDATA);
            $from_username = $post_obj->FromUserName;
            $this->log_file("../logs/debug.log", $from_username);
            $to_username = $post_obj->ToUserName;
            $MsgType = $post_obj->MsgType;

            $recieve_time = $post_obj->CreateTime;

            $recieve_datetime = date("Y-m-d H:i:s", (int)$recieve_time);

            if ($MsgType=="text") {
                $message = trim($post_obj->Content);
                $msgid = $post_obj->MsgId;

                sql_or_die(sprintf("insert into recieved_text (user_name, date_time, content) 
                                    values('%s', '%s', '%s')", $from_username, $recieve_datetime, $message));

                if ($message == "ipad") {

                    $sql = ('select distinct code_name from award_user');
                    $ret = mysql_query($sql);
                    $user_code_names = array();
                    while ($row = mysql_fetch_assoc($ret)) {
                        $user_code_names[] = $row['code_name'];
                    }

                    $sql = ('select distinct code_name from promocodes');
                    $ret =mysql_query($sql);
                    $unused_code_names = array();
                    while ($row = mysql_fetch_assoc($ret)) {
                        $unused_code_names[] = $row['code_name'];
                    }

                    if (!$unused_code_names) {
                        $content_str = '很遗憾，您来晚了一步哦，所有的下载码都已经发完啦/撇嘴下次一定要眼疾手快呦/调皮,加入Q群171768524完成群主分配的小任务可以获取额外的下载码呦';
                        echo sprintf($text_tpl, $from_username, $to_username, $time, "text", $content_str);
        	            exit;

                    }

                    else {
                        while ($unused_code_name = array_pop($unused_code_names)) {
                            if (in_array($unused_code_name, $user_code_names))
                                continue;
                            else {
                                $sql = sprintf('select * from promocodes where code_name like "%s"', $unused_code_name);
                                $ret = mysql_query($sql);
                                $row = mysql_fetch_assoc($ret);
                                $code = $row['code'];
                                $code_name = $row['code_name'];
                                $content_str = sprintf("恭喜您获得一个【兰卡宝贝%s】下载链接!
                                                        在ipad里点击链接->
                                                        %s
                                                        就可以下载啦,希望您喜欢哦/可爱
                                                        链接有效期两天，希望您尽快使用，过期就不能再获取该app的下载码了哦
                                                        更多系列app请关注公众号lanka-baby。", $code_name, $code);
                                sql_or_die(sprintf('insert into award_user value("%s", "%s", "%s", "%s")', 
                                                     $from_username, $recieve_datetime, $code, $code_name)); 
                                sql_or_die(sprintf('delete from promocodes where code like "%s"', $code));
                                echo sprintf($text_tpl, $from_username, $to_username, $time, "text", $content_str);
        	                    exit;
                            }
                        }
                        $content_str = sprintf("您已经得到了所有的下载码啦/调皮，高抬贵手给别的小伙伴留点机会呗/抱拳");   
                        echo sprintf($text_tpl, $from_username, $to_username, $time, "text", $content_str);
        	            exit;
                    }
                }

                $sql = sprintf('select title, description, pic_url, url from news where 
                                title like "%%%1$s%%" or lable like "%%%1$s%%"', $message);
                $ret = mysql_query($sql);
                
                $stories = array();
                while ($row = mysql_fetch_assoc($ret)) {
                    array_push($stories, $row);
                }

                if (!$stories) {
                    $response_type = "text";
                    if ($message == '我要讲故事') {
                        $content_str = '谢谢您对我们的支持,您可以从现有的故事挑选喜欢的,讲完将音频发送给我们，加入q群171768524可以和更多家长一起交流';   
                    }
                    if ($message == '视频') {
                        $response_type = "music";
                    }

                    else {
                        $content_str = sprintf('不好意思，没有找到和【%s】相关的故事,换个词再试试吧。
                                                发送“目录”查看故事列表
                                                发送“我要讲故事”来给大家讲故事
                                                发送关键词如“公主、王子”查看故事
                                                =================
                                                如果喜欢我们的故事，戳右上角再戳右上角可以将美好的故事分享给您的好友，感谢您对我们的关注/爱心
                                                我们会一直努力为您的宝宝提供优质故事。
                                                希望您的宝宝健康成长', $message);
                    }
                }
                else {
                    $response_type = 'news';
                    shuffle($stories);
                    $story = $stories[0];
                    $title = $story['title'];
                    $description = $story['description'];
                    $pic_url = $story['pic_url'];
                    $url = $story['url'];
                    
                    $sql = sprintf('select title, description, pic_url, url from news 
                                    where title like "%%%1$s%%" or lable like "%%%1$s%%" limit 1', '儿童绘本');
                    $ret = mysql_query($sql);
                    $row = mysql_fetch_assoc($ret);
                    $pro_title = $row['title'];
                    $pro_description = $row['description'];
                    $pro_pic_url = $row['pic_url'];
                    $pro_url = $row['url'];
                }
            }

            else if ($MsgType=="event") {
                $event = $post_obj->Event;

                if ($event=="subscribe") {
                    $response_type = "text";
                    sql_or_die(sprintf("insert into stories_users (user_name, sub_time) values('%s', '%s')", $from_username, $recieve_datetime));
                    $msg_type = "text";
                    $content_str = '欢迎来到故事的王国
好的故事，可以给孩子幼小的心灵 种下美好的种子，伴随着他们的成长生根发芽。
希望您的宝宝能够在故事陪伴下健康成长。
=================
发送“目录”查看故事列表
发送“我要讲故事”来给我们的听众讲故事
回复关键词如“公主、王子”等查看故事
=================
在微信->通讯录->订阅号里点右上角的“+” 号
搜索"ertongshici"（“儿童诗词”的拼音）可以找到我们的儿童古诗订阅号
搜索“ergetongyao”（“儿歌童谣”的拼音）可以关注我们的儿歌订阅号
希望您和宝宝喜欢。';
                }
                else if ($event=="unsubscribe") {
                    $response_type = "text";
                    sql_or_die(sprintf("update stories_users set unsub_time = '%s' where unsub_time is null and user_name = '%s'", $recieve_datetime, $from_username));
                    $content_str = "一个用户离开了我们";
                    return;
                }

            }

            $time = time();
            if ($response_type == "text") {
                $msg_type = "text";
                $result_str = sprintf($text_tpl, $from_username, $to_username, $time, $msg_type, $content_str);
                echo $result_str;
                exit;
            }
                
            else if ($response_type == "news") {
                $response_news_tpl = sprintf($news_tpl, $from_username, $to_username, $time, 1, $each_item);
                $response_news = sprintf($response_news_tpl, $title, $description, 
                                    $pic_url, $url);
                echo $response_news;
                exit;
            }

            else if ($response_type = "music") {
                $title = '小鲤鱼跳龙门';
                $description = '专业主持人配音';
                $music_url = 'http://v.qq.com/boke/page/m/0/p/m0118r6b5jp.html';
                $hqmusic_url = 'http://v.qq.com/boke/page/m/0/p/m0118r6b5jp.html';

                $response_music = sprintf($music_tpl, $from_username, $to_username, $time, $title, $description, $music_url, $hqmusic_url);
                echo $response_music;
                exit;
            }

        }else{
        	echo "";
        	exit;
        }
    }

    private function check_signature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
        $token = TOKEN;
        $tmp_arr = array($token, $timestamp, $nonce);
        sort($tmp_arr);
        $tmp_str = implode( $tmp_arr );
        $tmp_str = sha1( $tmp_str );

        if( $tmp_str == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

?>
